package com.nineclock.system.processor;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
//@ConfigurationProperties(prefix = "huanxin.sms")
@Data
public class HXSendMessageProcessor implements SendMessageProcessor{
    @Value("${huanxin.orgName}")
    private String orgName;
    @Value("${huanxin.appName}")
    private String appName;
    @Value("${huanxin.clientId}")
    private String clientId;
    @Value("${huanxin.clientSecret}")
    private String clientSecret;
    @Value("${huanxin.tid}")
    private String tid;
    @Value("${huanxin.tm}")
    private String tm;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public Boolean sendSms(String phone, String code) {
        String tokenUrl = "http://a1.easemob.com/" + orgName + "/" + appName + "/token";
        Map<String,Object> tokenBody = new HashMap<>();
        tokenBody.put("grant_type", "client_credentials");
        tokenBody.put("client_id", clientId);
        tokenBody.put("client_secret", clientSecret);

        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json");

        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(tokenBody, headers);

        ResponseEntity<Map> entity = restTemplate.postForEntity(tokenUrl, request, Map.class);
        //token结果
        Map result = entity.getBody();

        String smsUrl = "http://a1.easemob.com/" + orgName + "/" + appName + "/sms/send";
        headers.add("Authorization","Bearer " + result.get("access_token"));
        Map<String,Object> messageBody = new HashMap<>();
        Map<String,String> codeMap  = new HashMap<>();
        codeMap.put(tm,code);
        String[] phoneNumber = {phone};
        messageBody.put("mobiles",phoneNumber);
        messageBody.put("tid",tid);
        messageBody.put("tmap",codeMap);
        messageBody.put("extendCode",null);
        messageBody.put("custom",null);
        HttpEntity<Map<String,Object>> messageRequest = new HttpEntity<Map<String, Object>>(messageBody,headers);
        ResponseEntity<Map> mapResponseEntity = restTemplate.postForEntity(smsUrl, messageRequest, Map.class);
        System.out.println(mapResponseEntity);
        return true;
    }

    @Override
    public boolean support(String restApi) {
        if ("a1.easemob.com".equals(restApi)){
            return true;
        }
        return false;
    }
}
